<?php

namespace Lettral\UserBundle\Controller;

use Lettral\UserBundle\Form\Type\UserProfileForm;

use FOS\UserBundle\Form\Model\CheckPassword;

use Lettral\UserBundle\Form\Type\UserProfileFormType;

use Lettral\UserBundle\Form\Type\UserPersonnalInfoForm;

use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Lettral\Helpers\ResponseCreator;
use FOS\UserBundle\Entity\UserManager;
use FOS\UserBundle\Controller\ProfileController as BaseController;

class ProfileController extends BaseController
{
	public function editAction()
	{
		$request = $this->container->get('request');
	
		$user = $this->container->get('security.context')->getToken()->getUser();
		if (!is_object($user) || !$user instanceof UserInterface) {
			throw new AccessDeniedException('Vous n\'avez pas le droit d\'accéder à cette section');
		}
	
		$form = $this->container->get('form.factory')->create(new UserProfileForm());
		$form->setData($user);
		
		if ($request->getMethod() == 'POST') {
	
			$form->bindRequest($request);
		
			$validator = $this->container->get('validator');
			$errors = $validator->validate($user, array('Profile'));
		
			if (count($errors) == 0)
			{
				$um = $this->container->get('fos_user.user_manager');
				$um->updateUser($user);		
				return ResponseCreator::getSuccess();
			}
			else
			{
				return ResponseCreator::getErrorList($errors);
			}
		}
		
		return $this->container->get('templating')->renderResponse('FOSUserBundle:Profile:edit.html.twig',
			array('form' => $form->createView(), 'theme' => $this->container->getParameter('fos_user.template.theme'))
		);
	}
	
    public function editPersonnalInfoAction()
    {          
    	$request = $this->container->get('request');
    	
    	$user = $this->container->get('security.context')->getToken()->getUser();     
    	if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('Vous n\'avez pas le droit d\'accéder à cette section');
        }   
        
        $form = $this->container->get('form.factory')->create(new UserPersonnalInfoForm());
        $form->setData($user);

        $form->bindRequest($request);
          
        $validator = $this->container->get('validator');
        $errors = $validator->validate($user, array('Profile'));
        
        if (count($errors) == 0) 
        {                  
        	$em = $this->container->get('doctrine.orm.entity_manager');               
            $em->persist($user);
            $em->flush();
                
            return ResponseCreator::getSuccess();
        }
		else 
		{
			return ResponseCreator::getErrorList($errors);
		}
    }
}